/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package domain.xml;

import domain.DomainController;
import domain.forumdata.Category;
import domain.forumdata.ForumCategory;
import domain.forumdata.forums.Generic;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import persistence.net.URLChecker;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 */
public class ForumImporter
{
    /**
     * Imports forums from XML.
     * @param xmlContent The XML.
     */
    public static void fromXML(String xmlContent)
    {
        try
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new ByteArrayInputStream(xmlContent.getBytes()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("forum");
            for(int i = 0; i < nodeList.getLength(); i++)
            {
                Node node = nodeList.item(i);
                if(node.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element element = (Element)node;
                    
                    String forumName = element.getAttribute("name");
                    String forumType = getValueFromNode(element, "type");
                    String forumLoginURL = getValueFromNode(element, "loginURL");
                    String forumUsername = getValueFromNode(element, "username");
                    char[] forumPassword = getValueFromNode(element, "password").toCharArray();

                    //Check if the forum is ok.
                    if(forumName.length() < 1 ||
                            !URLChecker.check(forumLoginURL, false) ||
                            forumUsername.length() < 1 ||
                            forumPassword.length < 1)
                    {
                        //tampering found!
                        continue; //Go to next forum, ignore this one.
                    }

                    Element categories = (Element)element.getElementsByTagName("categories").item(0);
                    NodeList nodeCatList = categories.getElementsByTagName("category");

                    ArrayList<ForumCategory> categoriesList = new ArrayList<ForumCategory>();
                    
                    for(int j = 0; j < nodeCatList.getLength(); j++)
                    {
                        Element cat = (Element)nodeCatList.item(j);
                        String categoryName = cat.getAttribute("name");
                        String categoryURL = cat.getAttribute("url");

                        Category c = DomainController.getInstance().getCategories().getCategoryByName(categoryName);

                        if(c == null)
                        {
                            //Create
                            DomainController.getInstance().getCategories().addCategory(categoryName);
                            c = DomainController.getInstance().getCategories().getCategoryByName(categoryName);
                        }

                        categoriesList.add(new ForumCategory(c, categoryURL));
                    }

                    while(DomainController.getInstance().getForums().isInList(forumName))
                        forumName += "*";

                    //At this time all generic...
                    DomainController.getInstance().getForums().addForum(new Generic(forumName, forumLoginURL, forumUsername, forumPassword, categoriesList));
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            DomainController.getInstance().getLogger().log(Level.SEVERE, "Can't import forums: {0}", e.getMessage());
        }
    }

    private static String getValueFromNode(Element element, String name)
    {
        Element e = (Element)element.getElementsByTagName(name).item(0);
        NodeList list = e.getChildNodes();
        return ((Node)list.item(0)).getNodeValue();
    }
}